package pres.seanlang.utility.android;

import android.app.Application;
import pres.seanlang.utility.ReflectUtils;

/**
 *  Android application包装
 */
public class AAppUtils {
    protected AAppUtils() { throw new UnsupportedOperationException("can't instance..."); }

    private static volatile Application APPLICATION_INSTANCE = null;

    public static void setApplication(Application app) {
        APPLICATION_INSTANCE = app;
    }

    private static Application getApplicationByReflect() {
        /*Class<?> clazz = ReflectUtils.toClass("android.app.ActivityThread");
        Object activityThread = ReflectUtils.instance(clazz, false);
        Object thread = ReflectUtils.get(clazz, activityThread, "sCurrentActivityThread");
        if(thread == null) { thread = ReflectUtils.invoke(clazz, activityThread, "currentActivityThread"); }
        if(thread == null) { return null; }

        Object app = ReflectUtils.invoke(clazz, activityThread, "getApplication");
        if(app == null) { return null; }

        return (Application) app;*/

        ReflectUtils.Wrapper wrapper = ReflectUtils.builder("android.app.ActivityThread", false);
        Object thread = wrapper.get("sCurrentActivityThread");
        if(thread == null) { thread = wrapper.invoke("currentActivityThread"); }
        if(thread == null) { return null; }

        Object application = wrapper.invoke("getApplication");
        return application == null ? null : (Application) application;
    }

    public static Application getApplication() {
        if(APPLICATION_INSTANCE != null) {
            return APPLICATION_INSTANCE;
        } else {
            return getApplicationByReflect();
        }
    }
}
